import React from 'react';
import Top from '../top/index.js';
import Nav from '../nav/index.js';
import './stockForm/stockForm.css';
import CascadeMultiSelect from 'uxcore/lib/CascadeMultiSelect';
import {Button, Checkbox, Table, Dialog, Select, Radio, Input, Pagination,DatePicker} from 'element-react';
import {Grid} from 'react-bootstrap';
import {Row} from 'react-bootstrap';
import {Col} from 'react-bootstrap';
import './stockForm/iconfont.css';
import './stockForm/orange.css';
import axios from 'axios';
import util from '../../assets/js/util.js';

const prameCon = '';

class StockForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dialogVisible: false,
            disabled: false,
            demo1: ['浙江'],
            isGoing:true,
            startDate: null,//开始时间
            value1:'',//导出得第一个input的数值;
            value2:'',//导出得低二个input得数值；
            exportFields: ["分站", "分拣中心", "再生资源品类", "散货存货量", "成品包", "成品包数", "服务亭存货量"],
            checkList: ['复选框 A'],
            classification: [{value:0,label:'选择全部'}],
            PackagingStation: [], //分拣中心字段
            daochu: [{value: 'Excel'}],
            currentPage: 1,//当前页码
            size: 20,//默认每页数据量
            value: '',
            totalNumber:0, //表格总数
            substationId:[],
            PackagingStationId:[],
            exportValue: "1",
            Checked: true,
            recyclArr:[],//全部分类得数组
            options: [],
            substationOpt:[{value:0,label:'请选择'}],//联动分站
            PackagingStationOpt:[{value:0,label:'请选择'}],//联动分拣中心数据
            PackagingS:[],//全部分拣中心
            totleSubId:[],//总的分站id
            totlePSId:[],//总的分拣中心id
            paramsL: {}, //初始传得值，在初始化得时候给值，以后改变；
            Width: 0,
            checkboxData: [  //导出字段数据
                {

                    name: "分站",
                    type: "subName"
                },
                {
                    name: "分拣中心",
                    type: "pkgName"
                },
                {
                    name: "再生资源品类",
                    type: "typeName"
                },
                {
                    name: "散货存货量",
                    type: "bulkPack"
                },
                {
                    name: "成品包",
                    type: "finishPack"
                },
                {
                    name: "成品包数",
                    type: "packageNum"
                },
                {
                    name: "服务亭存货量",
                    type: "houseStock"
                }
            ],
            columns: [
                {
                    label: "序号",
                    type: 'index'
                },
                {
                    label: "分站",
                    prop: "subName"
                },
                {
                    label: "分拣中心",
                    prop: "pkgName"
                },
                {
                    label: "再生资源品类",
                    prop: "typeName",
                    width: 120
                },
                {
                    label: "散货存货量(Kg)",
                    prop: "bulkPack",
                    width: 130
                },
                {
                    label: "成品包(Kg)",
                    prop: "finishPack",
                    width: 100

                },
                {
                    label: "成品包数",
                    prop: "packageNum"
                },
                {
                    label: "服务亭存货量(Kg)",
                    prop: "houseStock",
                    width: 150
                },
                {
                    label: "合计存货量(Kg)",
                    prop: "TotalInventory",
                    width: 130

                }
            ],
            data: []
        }
    };

    //数组去重方法;
    uniq(array) {
        var temp = []; //一个新的临时数组
        for (var i = 0; i < array.length; i++) {
            if (temp.indexOf(array[i]) == -1) {
                temp.push(array[i]);
            }
        }
        return temp;
    }

    //初始加载表格申请数据的函数
    getInfo() {
        var arrF = [] //分站得集合
        var arrDB = [] //分拣中心集合
        var arrP = []
        var _this = this;
        //获取分站和分拣中心;
        axios.post('/count/count/subsandpkgs').then((data) => {
            let substationS = data.data.data;
            substationS.forEach(function (item, index) {
                arrF.push(item.id)
                item.children.forEach(function (subItem, subIndex) {
                    arrDB.push(subItem.id)
                })

            })

            var arrL = arrF.join(",")
            var arrDBL = arrDB.join(",")
            this.setState({
                substationId:arrF,
                PackagingStationId:arrDB
            })
            //表格中得数据开始
            var forDate = Object.assign({}, {page: this.state.currentPage}, {isShowSub: 1}, {subs: arrL}, {pkgs: arrDBL}, {size: 20},{types:''})
            this.setState({
                paramsL: forDate
            })
            this.getTable();
            //    表格中得数据结束
        }).catch((e) => {
            console.log(e);
        })
        //获取分站和分拣中心数据结束
    }

    //获取联动中得数据开始;（需要更改）
    linkage() {
        var objList = []
        let arrLP = []
        axios.post('/count/count/searchallsubstations').then((data) => {
            var substationLD = data.data.data;
            substationLD.forEach(function (item, index) {
                arrLP.push(item.id)
                objList.push({
                    value: item.id,
                    label: item.name,
                    children: []
                })
            })
            objList.forEach((item, index) => {
                //   获取分拣中心数据开始；
                var objFor = new URLSearchParams();
                objFor.append("subId", item.value)
                axios.post('/count/count/selectpkgsbysubid', objFor).then((data) => {
                    let res = data.data.data;
                    res.forEach((subItem, subIndex) => {
                        let obj = {};
                        obj.value = subItem.id;
                        obj.label = subItem.siteName
                        item.children.push(obj);
                    });
                }).catch((e) => {
                    console.log(e);
                })
                //   获取分拣中心数据结束
            })
            this.setState({
                options: objList,
                demo1: arrLP
            })

        }).catch((e) => {
            console.log(e);
        })
    }
    //获取联动中得数据结束；
    //获取联动中分站分拣中心数据开始（以后要用）
    linkageLater(){
        axios.post('/count/count/subsandpkgs').then((data) => {
            var totalList = data.data.data;
            var totleIdList = []; //获取总得分站id
            var totlePSIdList = [] ;//总的分拣中心id
            var itemChild = []
            totalList.forEach(function(item,index){
                totleIdList.push(item.id)
                item.value = item.id
                item.label = item.name;
                delete item.id
                delete item.name;
                itemChild.push(item.children)
                item.children.forEach(function(subItem,subIndex){
                    totlePSIdList.push(subItem.id)
                    subItem.value = subItem.id
                    subItem.label = subItem.name;
                    delete subItem.id
                    delete subItem.name
                    delete subItem.children
                })
            })
            totalList.unshift({
                value:totleIdList,
                label:'选择全部',
                children:itemChild
            })

            this.setState({
                substationOpt:totalList,
                totleSubId:totleIdList,
                totlePSId:totlePSIdList,
                PackagingS:itemChild
            })

        }).catch((e) => {
            console.log(e);
        })
    }
    //获取联动中分站分拣中心数据结束

    //联动得分站选择事件开始（以后要用）
    FzChange(val){
        var _this = this;
        var PacStaOpt = [];
        val.forEach(function(item,index){
            if(!Array.isArray(item)){
                _this.state.substationOpt.forEach(function(subItem,subIndex){
                    if(item == subItem.value){
                        subItem.children.forEach(function(subItem,subIndex){
                            PacStaOpt.push(subItem)
                        })
                    }
                })
            }else if(Array.isArray(item)){
                _this.state.substationOpt.forEach(function(subItem,subIndex){
                    if(subItem.label == '选择全部'){
                        subItem.children.forEach(function(subItem,subIndex){
                            subItem.forEach(function(supItem,supIndex){
                                PacStaOpt.push(supItem)
                            })

                        })
                    }
                })
            }
        })
        var PacSta = Object.assign({}, this.state.paramsL,{subs:val})
        PacStaOpt.unshift({
            value:this.state.totlePSId,
            label:'选择全部'
        })
        this.setState({
            PackagingStationOpt:PacStaOpt,
            paramsL:PacSta
        })
    }
    //联动得选择事件结束
    //联动分拣中心选择事件开始（以后要用）
    DBChange(val){
        var PacStaL = Object.assign({}, this.state.paramsL,{pkgs:val})
        this.setState({
            paramsL:PacStaL
        })
    }
    //联动得分站选择事件结束
    //联动选择ok事件开始
    // LinkageMultiSelect(valueList, labelList, leafList){
    //     if(JSON.stringify(valueList) === '[]'){
    //         alert('分站选择不能为空')
    //         return false;
    //     }
    //     var DBList = []
    //     var _this = this;
    //     leafList.forEach((item, index) => {
    //         DBList.push(item.value)
    //     })
    //     var AlLevel = Object.assign({}, this.state.paramsL, {pkgs: DBList}, {subs: valueList})
    //     if(labelList[0] != leafList[0].label){
    //         var AlLevel = Object.assign({}, this.state.paramsL, {pkgs: DBList}, {subs: valueList})
    //         this.setState({
    //             substationId:valueList,
    //             PackagingStationId:DBList
    //         })
    //     }else{
    //         var AlLevel = Object.assign({}, this.state.paramsL, {pkgs: valueList})
    //         this.setState({
    //             PackagingStationId:valueList
    //         })
    //     }
    //
    //     this.setState({
    //         paramsL: AlLevel
    //     });
    //     var URLforDate = new URLSearchParams();
    //     for (var p in this.state.paramsL) {
    //         URLforDate.append(p, this.state.paramsL[p])
    //     }
    // }
    //联动选择ok事件结束
    //获取表格中得数据开始
    getTable() {
        var URLforDate = new URLSearchParams();
        for (var p in this.state.paramsL) {
            URLforDate.append(p, this.state.paramsL[p])
        }
        axios.post('/count/stock/list', URLforDate).then((data) => {
            // totalNumber  total
            // totalPage
            const totleNum = data.data.data.total
            const countList = data.data.data.data;
            var TotalIn = {};
            var TotalInArr = []
            countList.forEach(function(item,index){
                console.log(item)
                item.bulkPack = item.bulkPack/1000
                item.finishPack = item.finishPack/1000
                item.houseStock = item.houseStock/1000
                var TotalInNum = item.bulkPack+item.finishPack+item.houseStock
                TotalIn = Object.assign({}, item, {TotalInventory: TotalInNum})
                TotalInArr.push(TotalIn)
            })
            this.setState({
                data: TotalInArr,
                totalNumber:totleNum
            })
            if(this.state.totalNumber <=0){
                this.refs.pagina.style.display = 'none'
            }else{
                this.refs.pagina.style.display = 'block'
            }
        }).catch((e) => {
            console.log(e);
        })
    }
    //获取表格中得数据结束
    //单选框
    onChange(e) {
        this.setState({
            exportValue: e
        });
    }
    //确定导出
    exportSure() {
        var _this = this;
        var Export = {} //导出得对象；
        if(this.state.exportValue == "1"){
            this.setState({
                exportValue:"1"
            })
        }else if(this.state.exportValue == "2"){
            this.setState({
                exportValue:"2"
            })
        }else if(this.state.exportValue == "3"){
            this.setState({
                exportValue:"3"
            })
        }
        var _file = []
        this.state.exportFields.forEach(function(item,index){
            console.log(item)
            _this.state.checkboxData.forEach(function(subItem,index){
                if(item == subItem.name){
                    _file.push(subItem.type)
                }
            })
        })
        console.log(_file)
        if(this.state.exportFields.length<2) return alert('请至少勾选两项');
        window.open('/count/stock/export?subs='+this.state.substationId+'&pkgs='+this.state.PackagingStationId+'&searchtype='+this.state.exportValue+'&size='+10+'&begin='+this.state.value1+'&end='+this.state.value2+'&showFields='+_file.join(','))
    }
    //导出结束；
    //获取品类回收开始
    huishou() {
        var _this = this;
        axios.post('/count/count/selecttypes').then((data) => {
            if(data.data.code){
                this.props.history.push('/login')
            }
            var recycling = data.data.data;
            var recyclingList = []
            var recyclingArr = [] //全部得label；
            // classification
            recycling.forEach(function (item, index) {
                recyclingArr.push(item.id)
                recyclingList.push({
                    value: item.title,
                    label: item.id
                })
            })
            recyclingList.unshift({
                value:'选择全部',
                label: recyclingArr
            })
            recyclingList.unshift({
                value:'请选择',
                label: ''
            })
            this.setState({
                classification: recyclingList
            })
        }).catch((e) => {
            console.log(e);
        })
    }
    //搜索
    search() {
        var _this = this;
        var exportR = document.getElementById("exportRow")
        var exportList = exportR.getElementsByClassName("el-checkbox");
        //显示，隐藏分站；
        if (this.state.Checked == true) {
            exportList[0].style.display = "inline-block"
            console.log(this.state.startDate.toString())
            let recycleTypeId = Object.assign({}, this.state.paramsL, {isShowSub: 1},{schDate:util.formatDate(this.state.startDate)})
            this.setState({
                paramsL: recycleTypeId
            })
            setTimeout(function(){
                _this.getTable();
                // _this.show()
            },100)

        } else if(this.state.Checked == false){
            exportList[0].style.display = "none"
            let recycleId = Object.assign({}, this.state.paramsL, {isShowSub: 0})
            this.setState({
                paramsL: recycleId
            })
            setTimeout(function(){
                _this.getTable();
                // _this.hide()
            },100)
        }
    }
    //选择分站选项 复选框
    substation(e) {
        if (e == true) {
            this.setState({
                Checked: true
            })
        } else {
            this.setState({
                Checked: false
            })
        }
    }
    //分类选项发生变化时得事件
    recycling(e) {
        console.log(e)
        var val = e;
        var recycleTypeId = Object.assign({}, this.state.paramsL, {types: val})
        this.setState({
            paramsL: recycleTypeId
        })
    }
    //初始加载的
    componentWillMount() {
        this.linkageLater();
        this.huishou();
        this.getInfo();
        // this.linkage();
    }
    //导出第一个输入框输入事件
    TheInput1(e){
        this.setState({
            value1:e
        })
    }
    //导出第一个输入框输入事件
    TheInput2(e){
        this.setState({
            value2:e
        })
    }
    //导出弹框得选中值  //选择导出字段
    changeBox(e) {
        //e为导出弹框得选中值；
        this.setState({
            exportFields: e
        })
    }

    //分页改变页数的时候显示；
    onCurrentChange(e) {
        console.log(this.state.paramsL)
        var _this = this;
        let val = e;
        let dataPage = Object.assign({}, this.state.paramsL, {page: val})
        this.setState({
            currentPage: e,
            paramsL: dataPage
        })
        setTimeout(function () {
            _this.getTable()
        }, 500)
    }
    render() {
        return (
            <div className='inventory_bg'>
                <img src={require('../../assets/img/stockForm.png')} className='inventory_img'/>
                <Top/>
                <Nav stock="active" />
                <div className='inventory_wrap'>
                    <div className='inventory'>
                        <div className='show_cont'>
                            <Row className="data_temp data_temp1" style={{marginRight:0}}>
                                <div className="source source1">
                                    <div className="block dataTime1" style={{marginTop:'0'}}>
                                        <span className="demo" style={{padding:'0 15px'}}>日期：</span>
                                        <DatePicker
                                            value={this.state.startDate}
                                            placeholder="选择日期"
                                            onChange={date=>{
                                                this.setState({startDate: date})
                                            }}
                                        />
                                    </div>
                                </div>
                                <div className='select_box'>
                                    <span className='fenzhan'>分站：</span>
                                    <Select value={this.state.value} multiple={true} onChange={this.FzChange.bind(this)} className='selectKuang'>
                                        {
                                            this.state.substationOpt.map(el => {
                                                return <Select.Option key={el.value} label={el.label} value={el.value} />
                                            })
                                        }
                                    </Select>
                                </div>
                                <div  className='select_box'>
                                    <span className='fenzhan'>分拣中心：</span>
                                    <Select value={this.state.value} multiple={true} onChange={this.DBChange.bind(this)} className='selectKuang'>
                                        {
                                            this.state.PackagingStationOpt.map(el => {
                                                return <Select.Option key={el.value} label={el.label} value={el.value} />
                                            })
                                        }
                                    </Select>
                                </div>
                                <div  className='select_box'>
                                    <span className='fenzhan'>分类：</span>
                                    {/*下拉框*/}
                                    <Select value={this.state.value} clearable={true} className='selectKuang'
                                            onChange={this.recycling.bind(this)}>
                                        {
                                            this.state.classification.map((el, index) => {
                                                return <Select.Option key={index} label={el.value} value={el.label}/>
                                            })
                                        }
                                    </Select>
                                </div>
                                <div className="empty" style={{flex: '1'}}></div>
                                <div className='searchRight'>
                                    <div className='el-checkbox'>
                                        {/*多选框*/}
                                        <Checkbox className='substation xianshi' onChange={this.substation.bind(this)}
                                                  checked={this.state.Checked}>显示分站</Checkbox>
                                    </div>
                                        <Button type="suosou" onClick={this.search.bind(this)} className='el-button el-button--default'><i class="el-icon-search mr-6"></i>搜索</Button>
                                        <Button type="daochu"
                                                onClick={() => this.setState({dialogVisible: true})} className='el-button el-button--default'><i class="el-icon-upload mr-6"></i>导出</Button>
                                </div>
                            </Row>
                        </div>
                        {/*导出提示框开始*/}
                        <Dialog
                            title="导出"
                            size="tiny"
                            visible={this.state.dialogVisible}
                            onCancel={() => this.setState({dialogVisible: false})}
                            lockScroll={false}
                        >
                            <Dialog.Body>
                                <div className='rowP'>
                                    <span className='daochuwei'>导出为</span>
                                    <Select value="1" placeholder="请选择导出方式" className='daochuW' style={{width:'160px'}}>
                                        <Select.Option label="Excel" value="1"></Select.Option>
                                    </Select>
                                </div>
                                <div className='rowP'>
                                    <Radio value="1" checked={this.state.exportValue === "1"}
                                           onChange={this.onChange.bind(this)}>全部记录</Radio>
                                    <Radio value="2" checked={this.state.exportValue === "2"}
                                           onChange={this.onChange.bind(this)}>当前记录</Radio>
                                    <Radio value="3" checked={this.state.value === "3"}
                                           onChange={this.onChange.bind(this)}>从</Radio>
                                    <Input className='oneInp' onChange={this.TheInput1.bind(this)}/>
                                    <span className='dao'>到</span>
                                    <Input className='twoInp' onChange={this.TheInput2.bind(this)}/>
                                    <span className='dao'>页</span>
                                </div>
                                <div className='rowP'>导出字段</div>
                                <div className='rowP' id='exportRow'>
                                    <Checkbox.Group value={this.state.exportFields} onChange={this.changeBox.bind(this)}>
                                        {
                                            this.state.checkboxData.map((item, index) => {
                                                return <Checkbox key={index} label={item.name} ></Checkbox>
                                            })
                                        }
                                    </Checkbox.Group>
                                </div>
                            </Dialog.Body>
                            <Dialog.Footer className="dialog-footer">
                                <Button onClick={() => this.setState({dialogVisible: false})}
                                        className='quxiao'>取消</Button>
                                <Button type="primary" onClick={() => this.setState({dialogVisible: false})}
                                        onClick={this.exportSure.bind(this)} className='queding'>确定</Button>
                            </Dialog.Footer>
                        </Dialog>
                        {/*导出提示框结束*/}

                    </div>
                    <div>
                        <Table
                            style={{width: '100%'}}
                            columns={this.state.columns}
                            data={this.state.data}
                            label={"afdsfafs"}
                            showSummary={true}
                            summaryMethod={(columns, data) => {
                                const dataList = [];
                                for (var i = 0; i < columns.length; i++) {
                                    let total = 0;
                                    for (let j = 0; j < data.length; j++) {
                                        let value = data[j][columns[i]['property']];

                                        if (i == 0) {
                                            total = '总价 '
                                            break;
                                        }
                                        if (isNaN(value)) {
                                            total = ' '
                                            break;
                                        } else {
                                            total += parseFloat(value);
                                        }
                                    }
                                    dataList[i] = isNaN(total) ? total : total;
                                }
                                return dataList;
                            }}
                            onSelectChange={(selection) => {
                                console.log(selection)
                            }}
                            onSelectAll={(selection) => {
                                console.log(selection)
                            }}
                        />
                        <div className="block" ref='pagina'>
                            <Pagination
                                layout="total, prev, pager, next, jumper"
                                total={this.state.totalNumber}
                                pageSize={20}
                                currentPage={this.state.currentPage}
                                className='page'
                                onCurrentChange={this.onCurrentChange.bind(this)}
                            />
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default StockForm;